<template>
  <view @click="openAuth('WRITE_EXTERNAL_STORAGE')">
    <u-form-item :required="item.required" :label="$t(item.label)" :key="item.key">
      <!--            <u-upload :action="action"-->
      <!--                      :file-list="item.value"-->
      <!--                      :max-size="imageMaxSize"-->
      <!--                      :width="width"-->
      <!--                      :height="height"-->
      <!--                      :auto-upload="autoUpload"-->
      <!--                      :show-upload-list="showUploadList"-->
      <!--                      :del-bg-color="delBgColor"-->
      <!--                      :del-color="delColor"-->
      <!--                      :upload-text="uploadText"-->
      <!--                      :limit-type="limitType"-->
      <!--                      @on-success="onSuccess"-->
      <!--                      @on-remove="onRemove"-->
      <!--            >-->
      <!--            </u-upload>-->
      <view >
        <view class="filePreview">
          <view class="item" v-if="filesLoading" v-for="(item, index) in showDataList" :key="index">
            <view class="text" v-if="item.name">
              {{ item.name.substring(item.name.length, item.name.length - 20) }}
            </view>
            <view class="text" v-else-if="item.fileName">
              {{ item.fileName.substring(item.fileName.length, item.fileName.length - 20) }}
            </view>
            <view class="text" v-else>
              {{ item.url.substring(item.url.length, item.url.length - 20) }}
            </view>
            <view class="delete" @click="deleteUploadList(index)">X</view>
          </view>
        </view>
        <view v-if="plat!='app'" class="addFiles" @click="chooseFiles">{{ $t('点击上传文件') }}</view>
        <view v-if="plat=='app'">
			<upload @change="upload" v-if="flag==2"></upload>
			<upload @change="upload" v-if="flag==1" :text="'点击上传文件'"></upload>
		</view>
      </view>
    </u-form-item>
	
<!-- 	<yk-authpup ref="authpup" type="top" @changeAuth="changeAuth" :permissionID="permissionID"></yk-authpup> -->
	
	
  </view>
</template>
<script>
import ykAuthpup from "@/components/yk-authpup/yk-authpup";
import {HTTP_REQUEST_URL, FILE_MAX_SIZE, FILE_MAX_COUNT} from '@/config/app';
import upload from "@/components/buildForm/upload.vue";
export default {
  components:{
	 upload,ykAuthpup 
  },
  props: {
    item: {
      type: Object,
      default: {},
      required: true
    },
	flag:{
		type: [String, Number],
		default:1
	}
  },
  data() {
    return {
      uploadDataList: [],
      action: HTTP_REQUEST_URL + '/common/upload',
      imageMaxSize: FILE_MAX_SIZE,
      imageMaxCount: FILE_MAX_COUNT,
      width: 150,
      height: 150,
      autoUpload: true,
      showUploadList: true,
      delBgColor: '#fa3534',
      delColor: '#ffffff',
      uploadText: this.districts(this.$t('选择文件')),
      limitType: ['doc', 'xls', 'ppt', 'pdf', 'docx', 'xlsx', 'pptx'],
      showDataList: [],
      filesLoading: false,
      plat:uni.getStorageSync('plat'),
	  platform:'',
	  permissionID: 'WRITE_EXTERNAL_STORAGE',
	  permisesions: [
	  	{
	  		key: "WRITE_EXTERNAL_STORAGE",
	  		value: false
	  	},{
	  		key: "CAMERA",
	  		value: false,
	  	}
	  ]
    };
  },
  mounted() {
	if((this.item.value==undefined)||(this.item.value=='undefined')){
		this.item.value = []
	}
  
    if((this.item)&&(this.item.value)){
    	this.showDataList = JSON.parse(JSON.stringify(this.item.value))
    	this.uploadDataList = JSON.parse(JSON.stringify(this.item.value))
    }
    
		
    this.filesLoading = true
	
	
	const systemInfo = uni.getSystemInfoSync();
	const platform = systemInfo.platform;
	this.platform = platform
	if (platform != 'ios') {
		this.requestAndroidPermission('camera')
		this.requestAndroidPermission('photoLibrary')
	}
	
	
  },
  methods: {
	async requestAndroidPermission(id) {
		var that = this
		var result = await permision.requestAndroidPermission(id)
		console.log(id,result)
		// if(result!=0){
		// 	for(var i=0;i<that.permisesions.length;i++){
		// 		if(that.permisesions[i].key=='CAMERA'){
		// 			that.permisesions[i].value = true
		// 		}
		// 	}
		// }
	},
	async requestAndroidPermission2(id) {
		var that = this
		var result = await permision.requestAndroidPermission(id)
		console.log(id,result)
		// if(result!=0){
		// 	for(var i=0;i<that.permisesions.length;i++){
		// 		if(that.permisesions[i].key=='WRITE_EXTERNAL_STORAGE'){
		// 			that.permisesions[i].value = true
		// 		}
		// 	}
		// }
	},
	//打开自定义权限目的弹框
	openAuth(permissionID='') {
		//this.openAuth('CAMERA')
		
		// App.vue里面用新的组件啦
		// if (this.platform != 'ios') {
		// 	const not = this.permisesions.find(item => item.value === false);
		// 	if(not){
		// 		this.permissionID = not.key;
		// 		setTimeout(() => {
		// 			this.$refs['authpup'].open();
		// 		}, 500)
		// 	}
		// }
		//这个是对应的权限 ACCESS_FINE_LOCATION 位置权限 / WRITE_EXTERNAL_STORAGE 存储空间/照片权限 / CAMERA相机权限 / CALL_PHONE 拨打电话
	},
	//用户授权权限后的回调
	changeAuth() {
		const currentPermission = this.permisesions.find(item => item.key === this.permissionID);
		currentPermission.value = true
		//这里是权限通过后执行自己的代码逻辑
		console.log('权限已授权，可执行自己的代码逻辑了');
		this.openAuth()
	},
    districts(val) {
      return val.length > 6 ? val.slice(0, 6) + "..." : val
    },
    onSuccess(data, index, lists, name) {// 上传成功
      this.setFromData(lists)
    },
    onRemove(index, lists, name) {

      this.setFromData(lists)
    },
    setFromData(lists) {
      let formData = [];
      if (lists.length > 0) {
        for (let i = 0; i < lists.length; i++) {
          if (lists[i].response) {
            let temp = {
              url: lists[i].response.data.url
            }
            formData.push(temp)
          } else if (lists[i].url) {
            let temp = {
              url: lists[i].url
            }
            formData.push(temp)
          }
        }
      } else {
        formData = []
      }
      // console.log('formData', formData)
      this.$emit('change', this.item.key, formData)
    },
    chooseFiles() {
      const that = this
      // #ifdef MP-WEIXIN
      uni.chooseMessageFile({
        count: 6,
        type: 'file',
        extension: that.limitType,
        success: function (res) {
          console.log('chooseMessageFile', res)
          const tempFilePaths = res.tempFiles
          const tempFiles = res.tempFiles
          for (let i = 0; i < tempFilePaths.length; i++) {
            that.uploadFile(tempFilePaths[i].path, tempFiles[i])
          }
        }
      });
      // #endif
      // #ifdef H5
      uni.chooseFile({
        count: 6,
        extension: that.limitType,
        success: function (res) {
          const tempFilePaths = res.tempFilePaths
          const tempFiles = res.tempFiles
          for (let i = 0; i < tempFilePaths.length; i++) {
            that.uploadFile(tempFilePaths[i], tempFiles[i])
          }
        }
      });
      // #endif
      // #ifdef APP-PLUS
      console.log('APP')
      const lemonjkFileSelect = uni.requireNativePlugin('lemonjk-FileSelect');
      //提示：
      //1.不要忘了在 "manifest.json -> APP原生插件配置" 内添加本插件，否则云打包（离线打包）不会生效 showNativePicker
      lemonjkFileSelect.showPicker({
        //各属性配置见下方【showPicker可配置参数说明】
        pathScope: "/Download",
        mimeType: "*/*",
        utisType: "public.data",
        multi: 'yes',
        // securityPackageName: "com.android.egg",
        // securityScope: 'data'
      }, result => {
        // 返回值说明见下方【showPicker返回值说明】
        console.log('result', result)
        // （仅安卓）当错误码为1001，即未授权文件读取权限,可以提示用户未打开读取文件权限，并跳转设置页
        if (result.code == 1001) {
          uni.showModal({
            title: that.$t("需要文件访问权限"),
            content: that.$t("您还未授权本应用读取文件。为保证您可以正常上传文件，请在权限设置页面打开文件访问权限"),
            confirmText: that.$t("去授权"),
            cancelText: that.$t("算了"),
            success(e) {
              if (e.confirm) {
                // 跳转到应用设置页
                lemonjkFileSelect.gotoSetting();
              }
            }
          })
        }
        const tempFilePaths = result.files
        for (let i = 0; i < tempFilePaths.length; i++) {
          uni.showLoading({
            title: that.$t('上传中')
          })
          // 20秒没传完，关闭提示
          setTimeout(() => {
            uni.hideLoading()
          }, 20000)
          that.uploadFile(tempFilePaths[i].filePath, tempFilePaths[i])
        }
      })
      // #endif
    },
    uploadFile(file, showFile) {
      const that = this
      if (showFile.size) {
        if (showFile.size > 52428800) {
          that.$u.toast(that.$t('上传文件过大'))
          return false
        }
      }
      if (showFile.fileSize) {
        if (showFile.fileSize > 52428800) {
          that.$u.toast(that.$t('上传文件过大'))
          return false
        }
      }
      this.showDataList.push(showFile)
      console.log('this.showDataList', this.showDataList)
      uni.uploadFile({
        url: that.action,
        filePath: file,
        name: 'file',
        success: (uploadFileRes) => {
          console.log('uploadFileRes', uploadFileRes)
          uni.hideLoading()
          const resData = JSON.parse(uploadFileRes.data)
          if (resData.code === 1) {
            let resUrl = {url: resData.data.url}
            that.uploadDataList.push(resUrl)
            that.$emit('change', that.item.key, that.uploadDataList)
          } else {
            that.$u.toast(resData.msg)
          }
        }
      });
    },
    deleteUploadList(index) {
      this.uploadDataList.splice(index, 1)
      this.showDataList.splice(index, 1)
      this.$emit('change', this.item.key, this.uploadDataList)
    },
	upload(e,data){
		console.log(e,data)
		var that = this
		
		that.showDataList= []
		that.showDataList.push(data)
		
		that.uploadDataList= []
		that.uploadDataList.push(data)
		that.$emit('change', that.item.key, that.uploadDataList)
	}
  }
}
</script>

<style lang="scss">
.addFiles {
  color: #F79B29;
}

.filePreview {
  display: flex;
  flex-direction: column;

  .item {
    display: flex;

    .text {
      color: #999999;
      width: 360rpx;
      overflow: hidden;
      word-wrap: break-word;
      word-break: break-all;
      white-space: normal;
    }

    .delete {
      font-size: 20rpx;
      width: 30rpx;
      height: 30rpx;
      background-color: #fa3534;
      color: #FFFFFF;
      border-radius: 50%;
      line-height: 30rpx;
      text-align: center;
    }
  }
}
</style>
